/* eslint-disable unicorn/prefer-string-replace-all */
export function handleParams(url: string, params: object): string {
  if (params && Object.keys(params).length > 0) {
    const hasQuery = url.includes('?')

    const queryString = Object.entries(params)
      .map(([key, value]) => `${key}=${value}`)
      .join('&')

    return `${url}${hasQuery ? '&' : '?'}${queryString}`
  } else {
    return url
  }
}

export function handleParamsWithoutUrl(params: object): string {
  return Object.entries(params)
    .map(([key, value]) => `${key}=${value}`)
    .join('&')
}

export function objectSerializer<
  T = any,
  U extends boolean = true,
  P = U extends true ? T[] : T,
>(pairData: P) {
  return JSON.stringify(pairData, null, 0)
}

export function objectDeserializer<T = any, U extends boolean = true>(
  pair: string,
  isArray?: U,
): U extends true ? T[] : T {
  return pair ? JSON.parse(pair) : isArray ? [] : {}
}

export function simplyObjectDeepClone<T extends Record<string, any>>(
  obj: T,
): T {
  console.info("内容: " + JSON.stringify(obj))
  const shallowCloneObj = JSON.parse(JSON.stringify(obj))
  
  if(shallowCloneObj !== null){
    Object.entries(shallowCloneObj).forEach(([key, value]) => {
      if (typeof value === 'object') {
        shallowCloneObj[key] = simplyObjectDeepClone(value as T[typeof key])
      }
    })
  }

  return shallowCloneObj
}


export function convertToChinese(num: number) {
    const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    const units = ['', '十', '百', '千', '万'];
    let str = '';
 
    if (num === 0) {
        return chineseNumbers[0];
    }
 
    for (let i = 0; num > 0; i++) {
        const digit = num % 10;
        if (digit !== 0) {
            str = chineseNumbers[digit] + units[i] + str;
        } else if (!str.startsWith(chineseNumbers[0])) {
            str = chineseNumbers[0] + str;
        }
        num = Math.floor(num / 10);
    }
 
    return str.replace(/^一十/, '十');
}
 
/**
 * 保留n位小数，不四舍五入
 * @param [n=1] 保留小数点后几位
 */
export function keepDigitDecimal(num: number, n = 1): number {
    // 小于零，先转正数计算
   if (num < 0) {
     return (Math.floor(-1 * num * 10 ** n) / 10 ** n) * -1;
   }
  
   return Math.floor(num * 10 ** n) / 10 ** n;
 }
